<?php
/**
 * Created by PhpStorm.
 * BuyUser: tengwei
 * Date: 2018/11/12
 * Time: 10:49
 */

namespace common\logics\buyuser;

use common\widgets\Request;
use common\widgets\Tool;
use yii\base\BaseObject;
use Yii;

class BuyUserLogic extends BaseObject implements IBuyUser
{
    /** @var \common\sources\read\buyuser\BuyUserAccess $RBuyUserAccess */
    private $RBuyUserAccess;
    /** @var \common\sources\write\buyuser\BuyUserAccess $WBuyUserAccess */
    private $WBuyUserAccess;
    /**  @var \common\sources\read\buyuser\BuyUserAcountAccess $RBuyUserAcountAccess */
    private $RBuyUserAcountAccess;
    /** @var  \common\sources\read\message\MesgAccess  $RMesgAccess */
    private $RMesgAccess;
    /** @var \common\sources\write\message\MesgAccess  $WMesgAcdess */
    private $WMesgAcdess;
    /** @var \common\sources\read\taskorder\TaskOrderAccess $RTaskOrderAccess  ****/
    private $RTaskOrderAccess;


    public function init()
    {
        $this->RBuyUserAccess = Yii::$container->get('RBuyUserAccess');
        $this->WBuyUserAccess = Yii::$container->get('WBuyUserAccess');
        $this->RBuyUserAcountAccess = Yii::$container->get('RBuyUserAcountAccess');
        $this->RMesgAccess = Yii::$container->get('RMesgAccess');
        $this->WMesgAcdess = Yii::$container->get('WMesgAccess');
        $this->RTaskOrderAccess = Yii::$container->get("RTaskOrderAccess");
        parent::init();
    }

    //注册
    public function register($data)
    {
        if(empty($data['phone'])){
            return Tool::returnJson($data = [],  401, '手机号码不能为空');
        }
        if(empty($data['password'])){
            return Tool::returnJson($data = [], 402, '密码不能为空');
        }
        if(empty($data['pwd_confirm'])){
            return Tool::returnJson($data = [],  403, '确认密码不能为空');
        }
        if(empty($data['qq'])){
            return Tool::returnJson($data = [], 405, 'qq不能为空');
        }
        if(empty($data['wx'])){
            return Tool::returnJson($data = [], 406, '微信不能为空');
        }
        if(empty($data['verifycode'])){
            return Tool::returnJson($data = [], 407, '验证码不能为空');
        }
        if(!(Tool::isPhone($data['phone']))){
            return Tool::returnJson($data = [], 408, '手机格式不正确');
        }
        if(!(Tool::isPassword($data['password']))){
            return Tool::returnJson($data = [], 409, '密码格式不对');
        }
        if ($data['password'] !== $data['pwd_confirm']) {
            return Tool::returnJson($data = [], 410, '两次输入的密码不一致');
        }
        $buyUser = $this->RBuyUserAccess->getBuyUserByPhone($data['phone']);
        if (!empty($buyUser)) {
            return Tool::returnJson($data = [], 411, '该手机号码已经注册,不能重新注册');
        }

        $smsArr = $this->RMesgAccess->getVerifyCode($data['phone'],0);
        if (intval($smsArr['verifycode']) !== intval($data['verifycode'])) {
            return Tool::returnJson($data = [], 412, '验证码输入有误');
        }
        $param = [];
        $param['phone'] = $data['phone'];
        $param['password'] = Yii::$app->security->generatePasswordHash($data['password']);
        $param['qq'] = $data['qq'];
        $param['wx'] = $data['wx'];
        $param['reg_time'] = time();
        $param['pid'] = $data['inviter_id'];
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $reg = $this->WBuyUserAccess->addBuyUser($param);
            if (!$reg) {
                $transaction->rollBack();
                return Tool::returnJson([], 413, '注册失败');
            }
            $res_code = $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
            if(!$res_code)
            {
                $transaction->rollBack();
                return Tool::returnJson([], 415, '验证码校验失败');
            }
            //判断是否是首次邀请
            if($data['inviter_id']>0)
            {
                $this->WBuyUserAccess->modifyInviter($data['inviter_id']);
                //判断邀请人下面有几个人
                $inviter_count = $this->RBuyUserAccess->getInviteCount(['buy_id'=> $data['inviter_id'],"role"=>1]);
                if($inviter_count == 1)
                {
                    $this->WBuyUserAccess->modifyFirstInviter(['is_first' =>1,"phone"=> $data['phone']]);
                }
            }

            $transaction->commit();
            return Tool::returnJson([], 200, '注册成功');
        } catch (\Exception $e) {
            $transaction->rollBack();
            return Tool::returnJson([], 523, '数据库异常'.$e->getMessage());
        }
    }

    //账号密码登陆
    public function login($data)
    {
        if (empty($data['phone']) || empty($data['password'])) {
            return Tool::returnJson($data = [], $code = 401, '用户名或密码不能为空');
        }
        $buyer = $this->RBuyUserAccess->getBuyUserByPhone($data['phone']);
        if (empty($buyer)) {
            return Tool::returnJson($data = [], $code = 402, '手机号还未注册，请先注册后登陆');
        }
        if($buyer['role'] !=1){
            return Tool::returnJson($data = [], $code = 405, '该手机非本平台账号,请重新输入');
        }
        if (!Yii::$app->security->validatePassword($data['password']."", $buyer['password'])) {
            return Tool::returnJson($data = [], $code = 403, '用户名或密码错误');
        }
        //获取用户中心数据
        $buyuserAccount = $this->RBuyUserAcountAccess->getBuyUserAccount($buyer['id']);
        $arr = array(
            'remain_funds' => isset($buyuserAccount['remain_funds']) ? $buyuserAccount['remain_funds'] : 0,
            'remail_golds' => isset($buyuserAccount['remail_golds']) ? $buyuserAccount['remail_golds'] : 0,
            'freezing_funds' => isset($buyuserAccount['freezing_funds']) ? $buyuserAccount['freezing_funds'] : 0,
            'freezing_golds' => isset($buyuserAccount['freezing_golds']) ? $buyuserAccount['freezing_golds'] : 0,
            'income_golds' => isset($buyuserAccount['income_golds']) ? $buyuserAccount['income_golds'] : 0,
        );
        $order_arr = [];
        $order_arr['waiting_submit_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>1]);
        $order_arr['waiting_goods_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>5]);
        $order_arr['confirm_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>7]);
        $order_arr['reject_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>9]);
        $order_arr['complete_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>8]);
        //获取任务垫付本金
        $buyuser_advance_amount = $this->RTaskOrderAccess->getBuyAdvanceFund(['buy_id'=> $buyer['id'],"order_status" => "2,3,4,5,6,7"]);
        $arr['advance_amount'] = isset($buyuser_advance_amount['advance_amount']) ? $buyuser_advance_amount['advance_amount'] :0;
        //修改登陆时间
        $this->WBuyUserAccess->modifyTime($buyer['id']);
        $buyer['useraccount'] = $arr;
        $buyer['task_order'] = $order_arr;
        return Tool::returnJson($buyer, $code = 200, '登陆成功');
    }


    //账号验证码登陆
    public function loginCode($data)
    {
        if(empty($data['phone'])){
            return Tool::returnJson($data = [], $code = 401, '账号不能为空');
        }
        if(empty($data['verifycode'])){
            return Tool::returnJson($data = [], $code = 402, '验证码不能为空');
        }
        $buyer = $this->RBuyUserAccess->getBuyUserByPhone($data['phone']);
        if (empty($buyer)) {
            return Tool::returnJson($data = [], $code = 403, '手机号还未注册，请先注册后登陆');
        }

        if($buyer['role'] !=1){
            return Tool::returnJson($data = [], $code = 406, '该手机非本平台账号,请重新输入');
        }
        $smsArr = $this->RMesgAccess->getVerifyCode($data['phone'],1);
        if ($smsArr['verifycode'] == $data['verifycode']) {
            //TODO：成功后跳转
            $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
            //获取用户中心数据
            $buyuserAccount = $this->RBuyUserAcountAccess->getBuyUserAccount($buyer['id']);
            //修改登陆时间
            $this->WBuyUserAccess->modifyTime($buyer['id']);
            if (empty($buyuserAccount)) {
                $buyuserAccount = array(
                    'remain_funds' => 0,
                    'remail_golds' => 0,
                    'freezing_funds' => 0,
                    'freezing_golds' => 0,
                    'income_golds' => 0
                );
                $buyer['useraccount'] = $buyuserAccount;
            }
            $buyer['useraccount'] = $buyuserAccount;
            $order_arr = [];
            $order_arr['waiting_submit_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>1]);
            $order_arr['waiting_goods_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>5]);
            $order_arr['confirm_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>7]);
            $order_arr['reject_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>9]);
            $order_arr['complete_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyer['id'],"order_status" =>8]);
            //获取任务垫付本金
            $buyuser_advance_amount = $this->RTaskOrderAccess->getBuyAdvanceFund(['buy_id'=> $buyer['id'],"order_status" => "2,3,4,5,6,7"]);
            $arr['advance_amount'] = isset($buyuser_advance_amount['advance_amount']) ? $buyuser_advance_amount['advance_amount'] :0;

            //修改登陆时间
            $this->WBuyUserAccess->modifyTime($buyer['id']);
            $buyer['task_order'] = $order_arr;
            return Tool::returnJson($buyer, $code = 200, '成功');
        } else {
            return Tool::returnJson($data = [], $code = 405, '验证码输入有误');
        }
    }

    //验证人机验证
    public function captcha($data)
    {
        $url = Yii::$app->params['captcha']['captcha_url'];
        $api_key = Yii::$app->params['captcha']['api_key'];
        $data['api_key'] = $api_key;
        return Request::curl_formdata($url, $data);
    }

    //修改密码
    public function modifyPassword($data)
    {
        if (empty($data['phone'])) {
            return Tool::returnJson($data = [], $code = 401, '手机号码不能为空');
        }
        if(empty($data['sms_code'])){
            return Tool::returnJson([],402,'短信验证码不能为空');
        }

        if(empty($data['newPwd'])){
            return Tool::returnJson([],403, '新密码不能为空');
        }
        if(empty($data['newPwd_confirm'])){
            return Tool::returnJson([],405, '确认密码不能为空');
        }

        if ($data['newPwd'] !== $data['newPwd_confirm']) {
            return Tool::returnJson($data = [], 406, '密码输入不一致');
        }
        //判断手机号码是否
        if(!Tool::isPhone($data['phone'])){
            return Tool::returnJson($data = [], 407, '手机号码格式不对');
        }
        //判断手机号码是否注册
        $buyers = $this->RBuyUserAccess->getBuyUser($data['phone']);
        if(empty($buyers)){
            return Tool::returnJson($data = [], 512, '该手机尚未注册');
        }

        if($buyers['role'] !=1){
            return Tool::returnJson($data = [],  513, '该手机非本平台账号,请重新输入');
        }

        //获取短信验证码
        $smsArr = $this->RMesgAccess->getVerifyCode($data['phone'],4);
        if($smsArr['verifycode'] != $data['sms_code']){
            return Tool::returnJson($data = [], 408, '手机短信验证码错误');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //加密密码
            $password_hash = Yii::$app->security->generatePasswordHash($data['newPwd']);
            $param['newPwd'] = $password_hash;
            $param['phone'] = $data['phone'];
           $result = $this->WBuyUserAccess->UpdatePwd($param);
           if($result){
               $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
               $transaction->commit();
               return Tool::returnJson($data = [], $code = 200, '修改密码成功');
           }
           $transaction->rollBack();
           return Tool::returnJson($data = [], $code = 409, '修改密码失败');
        } catch (\Exception $e) {
            $transaction->rollBack();
            return Tool::returnJson([], 510, '写入数据库失败,' . $e->getMessage());
        }
    }

    //忘记密码
    public function forgetPassword($data)
    {
        if (empty($data['phone'])) {
            return Tool::returnJson($data = [], $code = 401, '手机号码不能为空');
        }
        if(empty($data['verifycode'])){
            return Tool::returnJson($data = [], $code = 402, '短信验证码不能为空');
        }
        if(empty($data['newPwd'])){
            return Tool::returnJson($data = [], $code = 403, '新密码不能为空');
        }
        if(empty($data['newPwd_confirm'])){
            return Tool::returnJson($data = [], $code = 405, '确认新密码不能为空');
        }
        if ($data['newPwd'] !== $data['newPwd_confirm']) {
            return Tool::returnJson($data = [], $code = 406, '密码输入不一致');
        }
        //判断手机号码是否是正确格式
        if(!Tool::isPhone($data['phone'])){
            return Tool::returnJson($data = [], 407, '手机号码格式不对');
        }
        //判断手机号码是否注册
        $buyers = $this->RBuyUserAccess->getBuyUser($data['phone']);
        if(empty($buyers)){
            return Tool::returnJson($data = [], 512, '该手机尚未注册');
        }
        if($buyers['role'] !=1){
            return Tool::returnJson($data = [],  513, '该手机非本平台账号,请重新输入');
        }
        //获取短信验证码
        $smsArr = $this->RMesgAccess->getVerifyCode($data['phone'],3);
        if($smsArr['verifycode'] != $data['verifycode']){
            return Tool::returnJson($data = [], 408, '手机短信验证码错误');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //加密密码
            $password_hash = Yii::$app->security->generatePasswordHash($data['newPwd']);
            $data['newPwd'] = $password_hash;
            $result = $this->WBuyUserAccess->UpdatePwd($data);
            if($result){
                $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
                $transaction->commit();
                return Tool::returnJson($data = [], $code = 200, '找回密码成功');
            }
            $transaction->rollBack();
            return Tool::returnJson($data = [], $code = 409, '找回密码失败');

        } catch (\Exception $e) {
            $transaction->rollBack();
            return Tool::returnJson([], 510, '写入数据库失败,' . $e->getMessage());
        }
    }

    public function modifyQQWx($param){
        if(empty($param['buy_id'])){
            return Tool::returnJson($data = [], 401, '买手账号id不能为空');
        }
        if(empty($param['qq']) && empty($param['wx'])){
            return Tool::returnJson($data = [], 402, 'qq或微信不能为空');
        }
        $buyers = $this->RBuyUserAccess->getBuyUserInfo($param['buy_id']);
        if(empty($buyers)){
            return Tool::returnJson($data = [], 403, '该账号不存在');
        }
        if($buyers['role'] !=1){
            return Tool::returnJson($data = [],  407, '该手机非本平台账号,请重新输入');
        }
        $arr = [];
        if(!empty($param['qq'])){
            $arr['qq'] = $param['qq'];
        }
        if(!empty($param['wx'])){
            $arr['wx'] = $param['wx'];
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $result = $this->WBuyUserAccess->modifyQQWX($param['buy_id'], $arr);
            if($result){
                $transaction->commit();
                return Tool::returnJson([],200,'修改成功');
            }
            $transaction->rollBack();
            return Tool::returnJson([],405,'修改失败');
        }catch (\Exception $e){
            $transaction->rollBack();
            return Tool::returnJson([],406,'修改异常'.$e->getMessage());
        }

    }
    public function setPayPwd($data){
        if (empty($data['phone'])) {
            return Tool::returnJson($data = [], $code = 401, '手机号码不能为空');
        }
        if(empty($data['sms_code'])){
            return Tool::returnJson($data = [], $code = 402, '短信验证码不能为空');
        }
        if(empty($data['newPwd'])){
            return Tool::returnJson($data = [], $code = 403, '新密码不能为空');
        }
        if(empty($data['newPwd_confirm'])){
            return Tool::returnJson($data = [], $code = 405, '确认新密码不能为空');
        }
        if ($data['newPwd'] !== $data['newPwd_confirm']) {
            return Tool::returnJson($data = [], $code = 406, '密码输入不一致');
        }
        //判断手机号码是否是正确格式
        if(!Tool::isPhone($data['phone'])){
            return Tool::returnJson($data = [], 407, '手机号码格式不对');
        }
        //判断手机号码是否注册
        $buyers = $this->RBuyUserAccess->getBuyUser($data['phone']);
        if(empty($buyers)){
            return Tool::returnJson($data = [], 510, '该手机尚未注册');
        }
        if($buyers['role'] !=1){
            return Tool::returnJson($data = [], 511, '该手机非本平台账号,请重新输入');
        }
        //获取短信验证码
        $smsArr = $this->RMesgAccess->getVerifyCode($data['phone'],7);
        if($smsArr['verifycode'] != $data['sms_code']){
            return Tool::returnJson($data = [], 408, '手机短信验证码错误');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //加密密码
            $password_hash = Yii::$app->security->generatePasswordHash($data['newPwd']);
            $arr['paypwd'] = $password_hash;
            $result = $this->WBuyUserAccess->setPayPwd($buyers['id'],$arr);
            if($result){
                $this->WMesgAcdess->modifyCodeStatus($smsArr['id']);
                $transaction->commit();
                return Tool::returnJson($data = [], $code = 200, '修改支付密码成功');
            }
            $transaction->rollBack();
            return Tool::returnJson($data = [], $code = 409, '修改支付密码失败');

        } catch (\Exception $e) {
            $transaction->rollBack();
            return Tool::returnJson([], 6000, '写入数据库失败,' . $e->getMessage());
        }
    }

    public function getBuyUserMessage($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([], 401, '买手id不能为空');
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],  402, '安全码不能为空');
        }
        if(md5($data['buy_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],  403, '安全码不正确');
        }
        $buyUser = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buyUser))
        {
            return Tool::returnJson([],  405, '买手账号不存在');
        }
        $buyUser['expire_time'] = isset($buyUser['expire_time']) ? date('Y-m-d H:i:s',$buyUser['expire_time']) : '';
        $buyAccount = $this->RBuyUserAcountAccess->getBuyUserAccount($data['buy_id']);
        if(empty($buyAccount))
        {
            $buyAccount = array(
                'remain_funds' => 0,
                'remail_golds' => 0,
                'freezing_funds' => 0,
                'freezing_golds' => 0,
                'income_golds' => 0
            );
        }
        //获取任务垫付本金
        $buyuser_advance_amount = $this->RTaskOrderAccess->getBuyAdvanceFund(['buy_id'=> $buyUser['id'],"order_status" => "2,3,4,5,6,7"]);
        $buyAccount['advance_amount'] = isset($buyuser_advance_amount['advance_amount']) ? $buyuser_advance_amount['advance_amount'] :0;
        $buyUser['useraccount'] = $buyAccount;

        $order_arr = [];
        $order_arr['waiting_submit_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyUser['id'],"order_status" =>1]);
        $order_arr['waiting_goods_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyUser['id'],"order_status" =>5]);
        $order_arr['confirm_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyUser['id'],"order_status" =>7]);
        $order_arr['reject_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyUser['id'],"order_status" =>9]);
        $order_arr['complete_count'] = $this->RTaskOrderAccess->getTaskOrderCount(['buy_id' =>$buyUser['id'],"order_status" =>8]);



        $buyUser['task_order'] = $order_arr;

        return Tool::returnJson($buyUser,200,"成功");
    }

}